using System;
using System.IO;
using UnityEngine;
using UnityEngine.Recorder;

namespace UTJ.FrameCapturer.Recorders
{
	[Recorder(typeof(EXRRecorderSettings), "Video", "UTJ/Legacy/OpenEXR")]
	[Obsolete("'UTJ/EXR' is obsolete, concider using 'Unity/Image Sequence' instead", false)]
	public class EXRRecorder : GenericRecorder<EXRRecorderSettings>
	{
		private static readonly string[] s_channelNames = new string[4]
		{
			"R",
			"G",
			"B",
			"A"
		};

		private fcAPI.fcExrContext m_ctx;

		public override bool BeginRecording(RecordingSession session)
		{
			if (!base.BeginRecording(session))
			{
				return false;
			}
			m_Settings.m_DestinationPath.CreateDirectory();
			m_ctx = fcAPI.fcExrCreateContext(ref m_Settings.m_ExrEncoderSettings);
			return m_ctx;
		}

		public override void EndRecording(RecordingSession session)
		{
			m_ctx.Release();
			base.EndRecording(session);
		}

		public override void RecordFrame(RecordingSession session)
		{
			if (m_Inputs.Count != 1)
			{
				throw new Exception("Unsupported number of sources");
			}
			BaseRenderTextureInput baseRenderTextureInput = (BaseRenderTextureInput)m_Inputs[0];
			RenderTexture frame = baseRenderTextureInput.outputRT;
			string path2 = m_Settings.m_BaseFileName.BuildFileName(session, base.recordedFramesCount, frame.width, frame.height, "exr");
			string path = Path.Combine(settings.m_DestinationPath.GetFullPath(), path2);
			fcAPI.fcLock(frame, delegate(byte[] data, fcAPI.fcPixelFormat fmt)
			{
				fcAPI.fcExrBeginImage(m_ctx, path, frame.width, frame.height);
				int num = (int)(fmt & (fcAPI.fcPixelFormat)7);
				for (int i = 0; i < num; i++)
				{
					fcAPI.fcExrAddLayerPixels(m_ctx, data, fmt, i, s_channelNames[i]);
				}
				fcAPI.fcExrEndImage(m_ctx);
			});
		}
	}
}
